import React, { PureComponent, useRef } from 'react'
import {
  Button, Form, Input, Modal, Popconfirm, TreeSelect,
} from 'antd'
import { DndProvider, useDrag, useDrop } from 'react-dnd'
import { HTML5Backend } from 'react-dnd-html5-backend'
import list2tree from 'list2tree'
import styles from './index.less'
import {
  BreadcrumbBar,
  HufuTreeTitle,
  ProTable,
  ProTableOperate,
  ProTableOptions,
  ProTree,
  searchTreeListByName,
} from '@/components'
import { regExp } from '@/utils/regExp'
import { deleteTheme, saveTheme, treeThemes } from './api'

const getNavTreeDataFunc = list2tree({
  idKey: 'id',
  parentIdKey: 'pid',
  newKey: {
    key: 'id',
    value: 'id',
    title: 'themeName',
  },
})

const menus = [{ name: '数据调研' }, { name: '主题设计' }]
const { OperateItem } = ProTableOperate
const { Item } = Form
const { TextArea } = Input

const type = 'DraggableBodyRow'
const DraggableBodyRow = ({
  index, moveRow, className, style, ...restProps
}) => {
  const ref = useRef()
  const [{ isOver, dropClassName }, drop] = useDrop({
    accept: type,
    collect: monitor => {
      const { index: dragIndex } = monitor.getItem() || {}
      if (dragIndex === index) {
        return {}
      }
      return {
        isOver: monitor.isOver(),
        dropClassName: dragIndex < index ? ' drop-over-downward' : ' drop-over-upward',
      }
    },
    drop: item => {
      moveRow && moveRow(item.index, index)
    },
  })
  const [, drag] = useDrag({
    type,
    item: { index },
    collect: monitor => ({
      isDragging: monitor.isDragging(),
    }),
  })
  drop(drag(ref))

  return (
    <tr
      ref={ref}
      className={`${className}${isOver ? dropClassName : ''}`}
      style={{ cursor: 'move', ...style }}
      {...restProps}
    />
  )
}

export default class ThemeDesign extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      columns: [
        {
          title: '名称',
          dataIndex: 'themeName',
          width: '22%',
          key: 'themeName',
        },
        // {
        //   title: '编码',
        //   dataIndex: 'code',
        //   width: '15%',
        //   key: 'code',
        // },
        {
          title: '描述',
          dataIndex: 'themeDesc',
          width: '22%',
          key: 'themeDesc',
          render: (text, record) => (!text || text === '' ? '--' : text),
        },
        {
          title: '创建人',
          dataIndex: 'creatorName',
          width: '22%',
          key: 'creatorName',
        },
        {
          title: '修改时间',
          dataIndex: 'updateTime',
          width: '24%',
          key: 'updateTime',
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '10%',
          key: 'operation',
          render: (text, record, index) => (
            <ProTableOptions>
              <span onClick={() => { this.onEditClick(record) }}>编辑</span>
              {/* <span onClick={this.onButtonClick}>上移</span>
              <span onClick={this.onButtonClick}>下移</span> */}
              <Popconfirm
                title="你确定要删除这个主题吗？"
                okText="确定"
                cancelText="取消"
                onConfirm={() => this.deleteTheme(record)}
              >
                <span>
                  删除
                </span>
              </Popconfirm>
            </ProTableOptions>
          ),
        },
      ],
      loading: false,
      visible: false,
      treeData: [],
      treeList: [],
      treeDataNew: [],
      selectedKeys: [],
      themeId: null,
      pid: null, // 编辑的时候记录下pid，在请求时要一起传
      query: {},
      treeDataOptions: [],
    }

    this.form = React.createRef()
  }

  componentDidMount() {
    this.getTreeThemes()
  }

  // 获取左侧列表方法
  getTreeThemes() {
    // 标记每个节点是第几层children
    const signLayerNum = (item, num = 0) => {
      item.layerNum = num
      if (num >= 5) {
        item.disabled = true
      }
      if (item.children) {
        item.children.map((child) => {
          const tempNum = num + 1
          signLayerNum(child, tempNum)
        })
      }
    }
    treeThemes().then(
      (res) => {
        const arr = getNavTreeDataFunc(res)
        // 给tree的数据标上第几层children
        arr.map((item) => {
          signLayerNum(item)
        })
        this.setState({
          treeData: arr,
          treeDataNew: arr,
          treeList: res || [],
        })
      },
      (error) => {
        console.log(error)
      },
    )
  }

  onEditClick = (data) => {
    // const { treeData } = this.state
    // const filterFun = (arr, disable = false) => arr.map((item) => {
    //   const obj = {
    //     key: item.key,
    //     title: item.title,
    //     value: item.value,
    //     disabled: !!item.disabled,
    //   }
    //   if (item.id === data.id || disable) {
    //     obj.disabled = true
    //     if (item.children) obj.children = filterFun(item.children, true)
    //   } else if (item.children) obj.children = filterFun(item.children)
    //   return obj
    // })
    // const treeDataOptions = filterFun(treeData)
    this.setState({
      visible: true,
      themeId: data.id,
      pid: data.pid,
      // treeDataOptions,
    }, () => {
      this.form.current && this.form.current.setFieldsValue({
        themeName: data.themeName,
        pid: data.pid,
        themeDesc: data.themeDesc,
      })
    })
  }

  showModal = (id) => {
    const { treeData } = this.state
    this.setState({
      visible: true,
      themeId: null,
      pid: null,
      treeDataOptions: treeData,
    }, () => {
      this.form.current && this.form.current.resetFields()
      if (id) {
        this.form.current && this.form.current.setFieldsValue({ pid: id })
      }
    })
  }

  closeModal = () => {
    this.setState({ visible: false })
  }

  // 删除主题
  deleteTheme = (data) => {
    this.setState({ loading: true })
    deleteTheme({ themeId: data.id }).then(
      (res) => {
        this.setState({ loading: false })
        this.fetchData()
        this.getTreeThemes()
      },
      (error) => {
        console.log(error)
        this.setState({ loading: false })
      },
    )
  }

  defaultIconFun = props => {
    const { selectedKeys } = this.state
    if (selectedKeys && selectedKeys[0] === props.data.key) {
      return props.expanded ? <i className="iconfont-colour2 icon-wenjianjia-dakaihover" /> : <i className="iconfont-colour2 icon-wenjianjia-morenhover" />
    }
    return props.expanded ? <i className="iconfont-colour2 icon-wenjianjia-dakai" /> : <i className="iconfont-colour2 icon-wenjianjia-moren" />
  }

  renderTreeNodes = (data) => {
    const tempArr = []
    data.map((item) => {
      const {
        title, children, layerNum, ...restProps
      } = item
      const tempObj = {
        icon: layerNum >= 5 ? true : this.defaultIconFun,
        ...restProps,
      }
      if (item.pid !== '0') {
        tempObj.title = (
          <HufuTreeTitle
            title={title}
            key={item.id}
            icon
            operations={layerNum < 5 ? [
              <a
                key={`new${item.id}`}
                onClick={() => this.showModal(item.id)}
              >
                新建主题
              </a>,
              <a
                key={`edit${item.id}`}
                onClick={() => this.onEditClick(item)}
              >
                编辑主题
              </a>,
              <Popconfirm
                title="你确定要删除这个主题吗？"
                okText="确定"
                cancelText="取消"
                onConfirm={() => this.deleteTheme(item)}
                key={`delPop${item.id}`}
              >
                <a
                  key={`del${item.id}`}
                >
                  删除主题
                </a>
              </Popconfirm>,
            ] : []}
          />
        )
      } else {
        tempObj.title = (
          <HufuTreeTitle
            title={title}
            key={item.id}
            icon
            operations={[
              <a
                key={`new${item.id}`}
                onClick={() => this.showModal(item.id)}
              >
                新建主题
              </a>,
            ]}
          />
        )
      }
      if (item.children) {
        tempObj.children = this.renderTreeNodes(item.children)
      }
      tempArr.push(tempObj)
    })
    return tempArr
  }

  onConfirm = () => {
    this.form.current.validateFields().then(values => {
      if (this.state.themeId) {
        values.themeId = this.state.themeId
        values.pid = this.state.pid
      }
      this.setState({ loading: true })
      saveTheme(values).then(
        (res) => {
          this.setState({
            loading: false,
            visible: false,
          })
          this.fetchData()
          this.getTreeThemes()
        },
        (error) => {
          this.setState({ loading: false })
          console.log(error)
        },
      )
    })
  }

  // moveRow = (dragIndex, hoverIndex) => {
  //   if (dragIndex === hoverIndex) return
  //   this.setState({ loading: true })
  //   let direction
  //   const moveThemeId = this.tableData[dragIndex].id
  //   const targetThemeId = this.tableData[hoverIndex].id
  //   if (dragIndex < hoverIndex) {
  //     direction = -1
  //   } else {
  //     direction = 1
  //   }
  //   moveTheme({
  //     direction,
  //     moveThemeId,
  //     targetThemeId,
  //   }).then(
  //     (res) => {
  //       this.setState({ loading: false })
  //       this.fetchData()
  //       this.getTreeThemes()
  //     },
  //     (error) => {
  //       console.log(error)
  //     },
  //   )
  // }

  onSelect = (selectedKeys) => {
    this.setState({
      selectedKeys,
      query: {
        pid: selectedKeys[0],
      },
    })
  }

  fetchData = async () => {
    const { selectedKeys } = this.state
    this.setState({
      query: {
        pid: selectedKeys[0],
      },
    })
  };

  render() {
    const {
      visible, themeId, treeList, treeDataNew, selectedKeys, loading, query, treeDataOptions,
    } = this.state
    const nameReg = regExp.name(2, 32)
    const nameReg2 = regExp.name(0, 128)
    return (
      <div className={`${styles.page_content_with_breadcrumb} ${styles.theme_design}`}>
        <BreadcrumbBar menu={menus} />
        <div className={styles.page_content}>
          <div className={styles.page_content_left}>
            <ProTree
              showLine
              showSearch
              showTitle={false}
              treeData={treeDataNew}
              renderTreeNodes={this.renderTreeNodes}
              selectedKeys={selectedKeys}
              onSelect={this.onSelect}
              ref={(dev) => (this.tree = dev)}
              search={(name) => {
                const searchTree = searchTreeListByName(
                  name,
                  treeList,
                  'themeName',
                )
                const treeDataNews = getNavTreeDataFunc(
                  searchTree.result,
                )
                this.setState(
                  {
                    treeDataNew: treeDataNews,
                  },
                  () => {
                    this.tree.onExpand(searchTree.fatchIds)
                  },
                )
              }}
            />
          </div>
          <div className={styles.page_content_right}>
            <ProTableOperate
              toggleOperate={false}
              unfolded
            >
              {/* <OperateItem align="left">
                <div className={styles.tip_str}>
                  <i className="iconfont icon-yiwentishi" />
                  拖动表格可以对主题进行排序
                </div>
              </OperateItem> */}
              <OperateItem itemType="btn">
                {
                  [
                    <Button
                      onClick={() => this.showModal()}
                      type="primary"
                      loading={loading}
                      key="new"
                    >
                      新建主题
                    </Button>,
                  ]
                }
              </OperateItem>
            </ProTableOperate>
            <DndProvider backend={HTML5Backend}>
              <ProTable
                url={query.pid ? '/api/v1/theme/listThemes' : null}
                query={query}
                columns={this.state.columns}
                loading={loading}
              // components={{
              //   body: {
              //     row: DraggableBodyRow,
              //   },
              // }}
              // onRow={(record, index) => ({
              //   index,
              //   moveRow: (dragIndex, hoverIndex) => { this.moveRow(dragIndex, hoverIndex) },
              // })}
              // getTableDataFinished={(data) => { this.tableData = data }}
              />
            </DndProvider>
          </div>
        </div>

        <Modal
          title={themeId ? '编辑主题' : '新增主题'}
          visible={visible}
          width={520}
          onCancel={this.closeModal}
          maskClosable={false}
          onOk={this.onConfirm}
          confirmLoading={loading}
        >
          <Form
            ref={this.form}
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 19 }}
            autoComplete="off"
          >
            <Item
              label="名称"
              name="themeName"
              rules={[
                { required: true, message: '请输入名称' },
                {
                  pattern: new RegExp(nameReg.reg, 'g'),
                  message: nameReg.text,
                },
              ]}
            >
              <Input placeholder="请输入名称" />
            </Item>
            {/* <Item
              label="编码"
              name="code"
              rules={[{ required: true, message: '请输入编码' }]}
            >
              <Input placeholder="请输入编码" />
            </Item> */}
            {
              !themeId && (
                <Item
                  label="主题"
                  name="pid"
                  rules={[{ required: true, message: '请选择主题' }]}
                >
                  <TreeSelect
                    showSearch
                    getPopupContainer={(triggerNode) => triggerNode.parentNode}
                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                    treeData={treeDataOptions}
                    placeholder="请选择主题"
                    treeDefaultExpandAll
                    filterTreeNode={(input, treeNode) => treeNode.title.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  />
                </Item>
              )
            }
            <Item
              label="描述"
              name="themeDesc"
              rules={[
                { required: false },
                {
                  pattern: new RegExp(nameReg2.reg, 'g'),
                  message: nameReg2.text,
                },
              ]}
            >
              <TextArea
                placeholder="请输入描述"
                rows={3}
              />
            </Item>
          </Form>
        </Modal>
      </div>
    )
  }
}
